/* ==================================================================   
 * Created [2009-4-27 下午11:32:55] by Jon.King 
 * ==================================================================  
 * TSS 
 * ================================================================== 
 * mailTo:jinpujun@hotmail.com
 * Copyright (c) Jon.King, 2009-2012 
 * ================================================================== 
 */

package com.jinhe.tss.cms.action;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jinhe.tss.cms.CMSConstants;
import com.jinhe.tss.cms.entity.ArticleScore;
import com.jinhe.tss.cms.helper.parser.ArticleScoreGridParser;
import com.jinhe.tss.cms.helper.parser.ScoreGridParser;
import com.jinhe.tss.cms.service.IScoreService;
import com.jinhe.tss.component.support.persistence.pagequery.PageInfo;
import com.jinhe.tss.component.support.web.webwork.PTActionSupport;
import com.jinhe.tss.core.exception.BusinessException;
import com.jinhe.tss.core.util.DateUtil;
import com.jinhe.tss.core.util.EasyUtils;
import com.jinhe.tss.core.web.dispaly.grid.GridDataEncoder;
import com.jinhe.tss.core.web.dispaly.xform.XFormEncoder;
 
public class ScoreAction extends PTActionSupport{

    private static final long serialVersionUID = 2676212810657258175L;
    
    private IScoreService service;
    
    private Long    articleId;      // 文章id
	private Long    commentId;     // 评论id
	private Integer score;          // 分数
	private String  commentContent; // 评论内容
	private String  mode;           // site:选定栏目，article：选定单篇文章
	private String  aspect;         // 统计类型：1-按作者;2-按文章;3-按栏目
	private Date    startTime = DateUtil.parse("1949-10-01");
	private Date    endTime   = DateUtil.parse("2049-10-01");
	private String  channelIds;
	private String  keywords;
	private String  author;
	private Integer page = 1;
    private String  type;
    
	/**
	 * 保存打分信息。
	 * 供门户中文章页上 打分 时调用。
	 */
	public String saveScoreInfo(){
        if ( articleId == null  || score == null ) 
            throw new BusinessException("评分失败，有非空数据项为空");

        ArticleScore scorerObj = new ArticleScore();
        scorerObj.setArticleId(articleId);
        scorerObj.setScoreTime(new Date());
        scorerObj.setScore(score);
        service.saveScoreInfo(scorerObj);

		return printSuccessMessage("感谢您的评分！");
	}
	
	/**
	 * 初始化统计查询XForm模板
	 * @return
	 */
	public String initScoreSearchXForm(){
		Map<String, Object> map = new HashMap<String, Object>();
		XFormEncoder xFormEncoder = new XFormEncoder(CMSConstants.XFORM_TEMPLATE_STATISTICS_SEARCH, map);
		if( aspect != null ){ 
			if(aspect.equals("1")){ // 文章作者排行榜
				xFormEncoder.setColumnAttribute("aspect", "editorvalue", "1|2|3");
				xFormEncoder.setColumnAttribute("aspect", "editortext", "文章作者排行榜|文章评分信息统计|栏目人气统计");
			} else if(aspect.equals("2")) { // 文章访问量统计
				if(mode.equals("site")){
					xFormEncoder.setColumnAttribute("aspect", "editorvalue", "2|1|3");
					xFormEncoder.setColumnAttribute("aspect", "editortext", "文章评分信息统计|文章作者排行榜|栏目人气统计");
				}
			} else if(aspect.equals("3")) { // 栏目人气统计
				xFormEncoder.setColumnAttribute("aspect", "editorvalue", "3|2|1");
				xFormEncoder.setColumnAttribute("aspect", "editortext", "栏目人气统计|文章评分信息统计|文章作者排行榜");
			}
		}
		return print("SearchInfo", xFormEncoder);
	}
	
	/**
	 * 得到文章打分结果(图表显示)
	 * @return
	 */
	public String getScoreResult(){
        List<?> list = null;
        if ("site".equals(mode)) { // 选定栏目
            list = service.findScoreInfoBySelectedChannels(channelIds, startTime, endTime, author);
        }
        else if ("article".equals(mode)) { // 单篇文章
            list = (List<?>) service.findScoreInfoByArticle(articleId)[0];
        }
        
        if ("1".equals(type)) {
            drawPie(list);
        } else if ("0".equals(type)) {
            drawBar(list);
        }
		return XML;
	}
    
    /** ***************************************** 生成统计图(start)******************************************** */
    /**
     * 生成饼状图
     */
    private void drawPie(List<?> scoreList) {
    	
    }

    /**
     * 生成柱状图
     */
    private void drawBar(List<?> scoreList) {
    	
    }
    /** ***************************************** 生成统计图(end) ******************************************** */
	
	/**
	 * <p>
	 * 得到评分结果（Grid显示）
	 * </p>
	 * @return
	 */
	public String getResult4Grid(){
        List<?> list;
		GridDataEncoder encoder;
		if( "1".equals(aspect) ) {
            list = service.findResult4Author(channelIds, startTime, endTime);
			encoder = new GridDataEncoder(list, CMSConstants.GRID_TEMPLATE_SCORE_COUNT, new ScoreGridParser());
		}
		else if( "3".equals(aspect) ) {
            // 没有文章的栏目不展示
            list = service.getResult4Channel(startTime, endTime);
			encoder = new GridDataEncoder(list, CMSConstants.GRID_TEMPLATE_SCORE_CHANNEL);
		}
		else {
			if("site".equals(mode)) {
                list = service.findScoreInfoBySelectedChannels(channelIds, startTime, endTime, author);
				encoder = new GridDataEncoder(new Object[]{list, "0.0"}, CMSConstants.GRID_TEMPLATE_CHANNEL_ARTICLE_SCORE, 
                        new ArticleScoreGridParser());
			} else {
                Object[] objs = service.findScoreInfoByArticle(articleId);
                list = (List<?>) ((Object[])objs)[0];
				encoder = new GridDataEncoder(objs, CMSConstants.GRID_TEMPLATE_ARTICLE_SCORE, new ArticleScoreGridParser());
			}
		}
		
        // 目前一律一页展示，不分页
        String info = getPageInfo(page, 10000, list.size());
		return print(new String[]{"ScoreCountList", "PageList"}, new Object[]{encoder, info});
	}
    
    /**
     * 分页信息
     */
    private String getPageInfo(int page, int pagesize, int totalRows){
        StringBuffer sb = new StringBuffer();
        sb.append("<pagelist totalpages=\"").append(totalRows % pagesize == 0 ? (totalRows / pagesize) : totalRows / pagesize + 1);
        sb.append("\" totalrecords=\"").append(totalRows);
        sb.append("\" currentpage=\"").append(page);
        sb.append("\" pagesize=\"").append(pagesize);
        return sb.append("\"/>").toString();
    }
	
	/*******************************************评论部分*********************************************/
	/**
	 * 保存评论信息。
     * 供门户中文章页上填写评论信息时调用。
	 */
	public String saveComments(){
		if( articleId == null  || commentContent == null )
			throw new BusinessException("文章ID或评论内容为空，评论失败！");
		
        service.saveComments(articleId, commentContent);
		return printSuccessMessage("感谢您的评论！");
	}
	
	/**
	 * 初始化评论页面
	 */
	public String initCommentsSearchXForm(){
        PageInfo pageInfo = service.getCommentListByArticle(articleId, 1);
        
		XFormEncoder xFormEncoder = new XFormEncoder( CMSConstants.XFORM_TEMPLATE_COMMENTS_SEARCH );
        GridDataEncoder gridEncoder = new GridDataEncoder(pageInfo.getItems(), CMSConstants.GRID_TEMPLATE_COMMENTS);
        return print(new String[]{"SearchInfo", "CommentList", "PageList"}, 
                new Object[]{xFormEncoder, gridEncoder, pageInfo});
	}
	
	/**
	 * <p>
	 * 得到评论信息
	 * </p>
	 * @return
	 */
	public String getCommentList() {
        PageInfo pageInfo = null;
		if ( !EasyUtils.isNullOrEmpty(keywords) ) {
            pageInfo = service.searchCommentList(keywords, page);
        } 
		else {
            pageInfo = service.getCommentListByArticle(articleId, page);
		}
		
        GridDataEncoder gridEncoder = new GridDataEncoder(pageInfo.getItems(), CMSConstants.GRID_TEMPLATE_COMMENTS);
        return print(new String[]{"CommentList", "PageList"}, new Object[]{gridEncoder, pageInfo});
	}
	
	/**
	 * <p>
	 * 删除评论信息
	 * </p>
	 * @return
	 */
	public String delComment(){
		service.delComments(commentId);
		return printSuccessMessage("删除成功！");
	}

	public void setArticleId(Long articleId) {
		this.articleId = articleId;
	}
	public void setScore(Integer score) {
		this.score = score;
	}
	public void setService(IScoreService service) {
		this.service = service;
	}
	public void setCommentContent(String commentContent) {
		this.commentContent = commentContent;
	}
	public void setMode(String mode) {
		this.mode = mode;
	}
	public void setChannelIds(String channelIds) {
		this.channelIds = channelIds;
	}
	public void setEndTime(Date endTime) {
        if( endTime != null ) {
            this.endTime = endTime;
        }
	}
	public void setStartTime(Date startTime) {
        if( startTime != null ) {
            this.startTime = startTime;
        }
	}
	public void setAspect(String aspect) {
		this.aspect = aspect;
	}
	public void setCommentId(Long commentId) {
		this.commentId = commentId;
	}
	public void setPage(Integer page) {
		this.page = page;
	}
	public void setKeywords(String keywords) {
		this.keywords = keywords;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
    public void setType(String type) {
        this.type = type;
    }
}	